import moment from 'moment'
import HTTP from '../libs/HTTP'
import { productDealerSpecDictUrl } from '../libs/api'

function setProductDict(params) {
  HTTP.post(productDealerSpecDictUrl(), params || {}, () => {}, (res) => {
    storage.save({
      key: 'productArray',
      data: res,
      expires: null
    })
  })
}


function getProductName(producerOrganNo, code, success, failure) {
  storage.load({
    key: 'productArray' + producerOrganNo
  }).then(ret => {
    success && success(ret[code])
  }).catch(err => {
    HTTP.post(productDealerSpecDictUrl(), {organNo: producerOrganNo}, () => {}, (res) => {
      storage.save({
        key: 'productArray' + producerOrganNo,
        data: res,
        expires: null
      })
      success && success(res[code])
    })
  })
}

let currentuser = {}
function setOnlyUserInfo(userinfo) {
  currentuser = userinfo
}

export function setLoginUserPwd(username, password) {
  storage.save({
    key: 'logindata',
    data: {
      username: username,
      password: password
    }
  })
}

export function getLoginUserPwd(callback) {
  storage.load({
    key: 'logindata'
  }).then((resp = {} )=> {
    const username = resp['username']
    const password = resp['password']
    callback(username, password)
  }).catch(err => {
    console.log(err)
  })
}

export function resetLoginUserPwd(username) {
  storage.save({
    key: 'logindata',
    data: {
      username: username
    }
  })
}


function setUserInfo(userinfo) {
  currentuser = userinfo
  storage.save({
    key: 'userinfo',
    data: userinfo
  })
}

function getDeepUserInfo(callback) {
  storage.load({
    key: 'userinfo'
  }).then(resp => {
    if(resp !== undefined) {
      setOnlyUserInfo(resp)
      callback(resp)
    }
  }).catch(err => {
    console.log(err)
  })
}

function getCurrentUser() {
  return currentuser
}

function getOrganNo() {
  return currentuser['organNo']
}

export function getDomain() {
  return currentuser['appDomain']
}

export function isProducer() {
  var result =  currentuser['appDomain'] == 'WINDER-PRODUCER'
  console.log('libs is result ', result)
  return result
}

function getArchId () {
  let userInfo = getCurrentUser() || {}
  return userInfo['archId']
}

function formatDateTime(d) {
  return moment(new Date(d)).format("YYYY-MM-DD HH:mm:ss")
}
function formatDate(d) {
  return moment(new Date(d)).format("YYYY-MM-DD")
}

function isNotBlank(v) {
  if(v == undefined || v == null || v == "") {
    return false
  } else {
    return true
  }
}

function isBlank(v) {
  return !isNotBlank(v)
}


export {
  currentuser,
  getCurrentUser,
  setOnlyUserInfo,
  getDeepUserInfo,
  setUserInfo,
  getOrganNo,
  getArchId,
  setProductDict,
  getProductName,
  formatDateTime,
  formatDate,
  isNotBlank,
  isBlank
}
